#coding=utf-8
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from AppManagement.models import K8sInfo,bind
from django.http import HttpResponse, HttpResponseRedirect
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

# Create your views here.

def set_response_data(code=0, data=None, error=None):
    return json.dumps({
        'code': code,
        'error_info': error,
        'data': data
    })


#集群信息
@login_required()
@csrf_exempt
def k8s_info(request):
    user_name = request.session.get('user_name')
    ret = {
        'Usersdata': [],
        'count': 0,
        'user_name': user_name,
    }
    if request.method == "GET":
        refresh = request.GET.get("refresh", None)
        if refresh:
            try:
                start = int(request.GET['offset'])
                end = start + int(request.GET['pageSize'])
                k8sinfo = K8sInfo.objects.filter(deleted=False)
                result = []
                for i in k8sinfo:
                    info = {
                        "id": i.id,
                        "cluster_name": i.cluster_name,
                        "config_file": i.config_file,
                        "api_server": i.api_server,
                        "api_token": i.api_token,
                    }
                    result.append(info)
                count = len(result)
                rows = result[start:end]
            except:
                rows = []
                count = 0,
            finally:
                return HttpResponse(set_response_data(data={'count': count, 'rows': rows}))
        else:
            return render(request, 'AppManagement/k8sinfo.html', ret)
    else:
        ###判断post参数  id存在的两种情况 编辑或删除
        if request.POST.get('id'):
            if request.POST.get('type'):
                id = request.POST.get('id')
                k8s = K8sInfo.objects.get(id=id)
                k8s.deleted = True
                k8s.save()
                return HttpResponse(json.dumps({"msginfo": u'集群信息删除成功'}))
            else:    ###修改集群信息
                id = request.POST.get('id')
                cluster_name = request.POST.get('cluster_name')
                config_file = request.POST.get('config_file')
                api_server = request.POST.get('api_server')
                api_token = request.POST.get('api_token')
                try:
                    k8s = K8sInfo.objects.get(id=id)
                    k8s.cluster_name = cluster_name
                    k8s.config_file = config_file
                    k8s.api_server = api_server
                    k8s.api_token = api_token
                    k8s.save()
                    return HttpResponse(json.dumps({"msginfo": u'集群信息修改成功'}))
                except Exception as e:
                    print(e)
                    return HttpResponse(json.dumps({"msgerror": u'集群信息修改失败'}))
        else:
            ###添加集群信息
            cluster_name = request.POST.get('cluster_name')
            config_file = request.POST.get('config_file')
            api_server = request.POST.get('api_server')
            api_token = request.POST.get('api_token')
            try:
                k8s = K8sInfo(
                    cluster_name=cluster_name,
                    config_file=config_file,
                    api_server=api_server,
                    api_token=api_token,
                    deleted=False
                )
                k8s.save()
                return HttpResponse(json.dumps({"msginfo": u'集群信息添加成功'}))
            except Exception as e:
                print(e)
                return HttpResponse(json.dumps({"msgerror": u'集群信息添加失败'}))

#环境绑定
@login_required()
@csrf_exempt
def cluseter_bind(request):
    user_name = request.session.get('user_name')
    ret = {
        'Usersdata': [],
        'count': 0,
        'user_name': user_name,
    }
    if request.method == "GET":
        refresh = request.GET.get("refresh", None)
        if refresh:
            try:
                start = int(request.GET['offset'])
                end = start + int(request.GET['pageSize'])
                bindinfo = bind.objects.all().filter(deleted=False)
                result = []
                for i in bindinfo:
                    info = {
                        "id": i.id,
                        "env_name": i.env_name,
                        "namespace": i.namespace,
                        "k8s_cluster": i.k8s_cluster,
                        "description": i.description,
                    }
                    result.append(info)
                count = len(result)
                rows = result[start:end]
                #获取所有集群 传给选框
                k8sinfo = K8sInfo.objects.values("cluster_name").filter(deleted=False)
                k8s_clusterinfo = []
                for bind_cluster in k8sinfo:
                    k8s_clusterinfo.append(bind_cluster.get('cluster_name'))
            except Exception as e:
                print e
                rows = []
                k8s_clusterinfo = []
                count = 0,
            finally:
                return HttpResponse(set_response_data(data={'count': count, 'rows': rows,'k8s_clusterinfo':k8s_clusterinfo}))
        else:
            return render(request, 'AppManagement/bind.html', ret)
    else:
    ###判断post参数  id存在的两种情况 编辑或删除
        if request.POST.get('id'):
            if request.POST.get('type'):
                id = request.POST.get('id')
                bindinfo = bind.objects.get(id=id)
                bindinfo.deleted = True
                bindinfo.save()
                return HttpResponse(json.dumps({"msginfo": u'环境删除成功'}))
            else:  ###修改集群信息
                id = request.POST.get('id')
                env_name = request.POST.get('env_name')
                description = request.POST.get('description')
                try:
                    binding = bind.objects.get(id=id).filter(deleted=False)
                    binding.env_name = env_name
                    binding.description = description
                    binding.save()
                    return HttpResponse(json.dumps({"msginfo": u'环境信息修改成功'}))
                except Exception as e:
                    print(e)
                    return HttpResponse(json.dumps({"msgerror": u'环境信息修改失败'}))
        else:
            ###增加绑定信息
            env_name = request.POST.get('env_name')
            namespace = request.POST.get('namespace')
            k8s_cluster = request.POST.get('k8s_cluster')
            description = request.POST.get('description')
            try:
                binding = bind(
                    env_name=env_name,
                    namespace=namespace,
                    k8s_cluster=k8s_cluster,
                    description=description,
                )
                binding.save()
                return HttpResponse(json.dumps({"msginfo": u'新增环境绑定成功'}))
            except Exception as e:
                print(e)
                return HttpResponse(json.dumps({"msgerror": u'新增环境绑定失败'}))

# @login_required()
# @csrf_exempt
# def project_list(request):
#     user_name = request.session.get('user_name')
#     ret = {
#         'Usersdata': [],
#         'count': 0,
#         'user_name': user_name,
#     }
#     if request.method == 'GET':
#         refresh = request.GET.get('refresh', None)
#         if refresh:
#             if request.GET['search_value'] == "":
#                 try:
#                     start = int(request.GET['offset'])
#                     end = start + int(request.GET['pageSize'])
#                     res_data = requests.post("http://opsproxy.kamennet.com:10958/RouterAPI", data=api_data, timeout=3)
#                     res_data_json = json.loads((res_data.content).replace('%','\\'))
#                     result = res_data_json['result']
#                     count = len(result)
#                     rows = result[start:end]
#                 except:
#                     rows = []
#                     count = 0,
#                 finally:
#                     return HttpResponse(set_response_data(data={'count': count,'rows': rows}))
#             else:
#                 search_value = request.GET['search_value']
#                 all_binduser = Get_binduserlist()
#                 rows = []
#                 for i in all_binduser:
#                     if i['ipaddr'].encode('utf-8') == search_value.encode('utf-8'):
#                         rows.append(i)
#                     elif i['mac'].encode('utf-8') == search_value.encode('utf-8'):
#                         rows.append(i)
#                 return HttpResponse(set_response_data(data={'count':1, 'rows': rows}))
#
#         else:
#             return render(request, 'network/ipbind_list.html',ret)
#     else:
#         place = request.POST.get('place')
#         ip = request.POST.get('ipaddr')
#         Rm_binduser_type = data_encryption("Rm_binduser")
#         data = {
#             'Type':Rm_binduser_type,
#             'index':place,
#             'ip':ip,
#         }
#         print data
#         try:
#             res_data = requests.post("http://opsproxy.kamennet.com:10958/RouterAPI",data=data,timeout=5)
#             res_data_json = json.loads(res_data.content)
#             res_data_status = res_data_json['error_code']
#             if res_data_status == "0":
#                 result = {'status': 'true', 'msginfo': u'用户已删除'}
#                 return HttpResponse(json.dumps(result))
#             else:
#                 result = {'status': 'true', 'msgerror': u'用户删除失败'}
#                 return HttpResponse(json.dumps(result))
#         except:
#             result = {'status': 'true', 'msgerror': u'接口请求错误'}
#             return HttpResponse(json.dumps(result))
